package cn.wolfcode.luowowo.comment.service.impl;

import cn.wolfcode.luowowo.comment.domain.TravelComment;
import cn.wolfcode.luowowo.comment.query.TravelCommentQuery;
import cn.wolfcode.luowowo.comment.respository.ITravelCommentRepository;
import cn.wolfcode.luowowo.comment.service.ITravelCommentService;
import com.alibaba.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;
import java.util.Optional;

@Service
public class TravelCommentServiceImpl implements ITravelCommentService {

    //拥有基本的crud功能和分页排序功能
    @Autowired
    private ITravelCommentRepository repository;
    //拥有较为底层的贾琏预置事,实现mongodb操作,这里用它来完成较为复杂的操作
    @Autowired
    private MongoTemplate template;


    @Override
    public Page query(TravelCommentQuery qo) {

        //查询条件
        Query query = new Query();

        if (qo.getTravelId() != -1){
            //攻略id的条件
            query.addCriteria(Criteria.where("travelId").is(qo.getTravelId()));
        }

        //查询总条数,结果类型
        long count = template.count(query, TravelComment.class);
        if (count==0){
            return Page.empty();
        }
        //分页,排序
        //当前页为0
        //每页显示条数
        //排序规则,参数1:asc还是desc,参数2:按照哪个参数进行排序
        PageRequest pageable = PageRequest.of(qo.getCurrentPage() - 1, qo.getPageSize(), Sort.by(Sort.Direction.DESC, "createTime"));
        query.with(pageable);
        //查询某一页
        List<TravelComment> list = template.find(query, TravelComment.class);
        return new PageImpl(list,pageable,count);
    }

    @Override
    public TravelComment save(TravelComment travelComment) {
        if (!StringUtils.hasLength(travelComment.getId())){
            travelComment.setCreateTime(new Date());
        }
        //如果该游记评论是评论的评论
        if (travelComment.getType()== TravelComment.TRAVLE_COMMENT_TYPE){
            Optional<TravelComment> op = repository.findById(travelComment.getRefComment().getId());
            //把评论和评论的评论一起保存
            travelComment.setRefComment(op.get());
        }
        repository.save(travelComment);
        return travelComment;
    }

    @Override
    public List<TravelComment> findFirstTen() {
        Query query = new Query();
        query.with(Sort.by(Sort.Direction.DESC, "createTime")).skip(1).limit(10);
        List<TravelComment> list = template.find(query, TravelComment.class);
        return list;
    }
}
